//
//  FMainAddView.m
//  FreeMark
//
//  Created by gaopr on 2019/2/17.
//  Copyright © 2019年 gaopr. All rights reserved.
//

#import "FMainAddView.h"
#import "FMCardView.h"
#import "HRColorPickerView.h"
#import "HRColorMapView.h"
#import "HRBrightnessSlider.h"
#import "CRColorPicker.h"
#import "FMColorPickerView.h"
#import "BHImagePicker.h"

@interface FMainAddView ()<UITextFieldDelegate,FMCardViewDelegate>

@property (nonatomic, weak) FMCardView *cardView;

@property (nonatomic, weak) FMColorPickerView *colorPickerView;


@end

@implementation FMainAddView

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        FMCardView *cardView = [[FMCardView alloc] init];
        cardView.delegate = self;
        [cardView.titleColorButton addTarget:self action:@selector(onColorEdit:) forControlEvents:UIControlEventTouchUpInside];
        [cardView.descLabelColorButton addTarget:self action:@selector(onColorEdit:) forControlEvents:UIControlEventTouchUpInside];
        [cardView.backGroundColorButton addTarget:self action:@selector(onColorEdit:) forControlEvents:UIControlEventTouchUpInside];
        [cardView.backGroundImageButton addTarget:self action:@selector(onChangedBackgroundImage:) forControlEvents:UIControlEventTouchUpInside];
        
        
        cardView.titleTextField.delegate = self;
        [self addSubview:cardView];
        _cardView = cardView;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}


- (void)onChangedBackgroundImage:(UIButton *)button
{
    [[BHImagePicker shareInstance] pickImageSourceType:UIImagePickerControllerSourceTypePhotoLibrary allowEdit:YES complete:^(BHImagePickerState status, UIImage *image) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status == BHImagePickerUnauthed)
            {
                [self showAlertWithString:@"相册未授权"];
            }
            else if (status == BHImagePickerUnavaiable)
            {
                [self showAlertWithString:@"相册不可用"];
            }
            
            if (image)
            {
                self.cardView.bgImageView.image = image;
            }
        });
    }];
}

- (void)showAlertWithString:(NSString *)string
{
    [[[UIAlertView alloc] initWithTitle:@"" message:string delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
}

- (void)keyboardChanged:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSTimeInterval animationDuration;
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    
    CGRect frameEnd = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    if (frameEnd.origin.y >= [UIScreen mainScreen].bounds.size.height)
    {
        //隐藏
        [UIView animateWithDuration:animationDuration animations:^{
            CGPoint cardCenter = self.cardView.center;
            cardCenter.y = 0.5 * self.bounds.size.height;
            self.cardView.center = cardCenter;
        }];
    }
    else
    {
        //显示
        CGFloat dy = frameEnd.size.height - (self.frame.size.height - CGRectGetMaxY(self.cardView.frame));
        if (dy > 0)
        {
            [UIView animateWithDuration:animationDuration animations:^{
                CGPoint cardCenter = self.cardView.center;
                cardCenter.y = 0.5 * self.bounds.size.height - dy;
                self.cardView.center = cardCenter;
            }];
        }
    }
}

#pragma mark - FMCardViewDelegate
- (void)onColorViewHidden:(FMCardView *)view
{
    self.colorPickerView.hidden = YES;
}

- (void)onColorViewEndEdit:(FMCardView *)view
{
    [self endEditing:YES];
}

- (void)onColorEdit:(UIButton *)button
{
    [self endEditing:YES];
    self.colorPickerView.onColorChanged = nil;
    self.colorPickerView.hidden = NO;
    if (button != self.cardView.backGroundColorButton)
    {
      [self.colorPickerView setColor:button.backgroundColor];
    }
    else
    {
       [self.colorPickerView setColor:self.cardView.backgroundColor];
    }
    __weak typeof(self) wself = self;
    self.colorPickerView.onColorChanged = ^(FMColorPickerView * _Nonnull view) {
        UIColor *color = [view getColor];
        
        if (wself.cardView.titleColorButton == button)
        {
            [button setBackgroundColor:color];
            wself.cardView.titleTextField.textColor = button.backgroundColor;
        }
        else if (wself.cardView.descLabelColorButton == button)
        {
            [button setBackgroundColor:color];
            wself.cardView.descTextView.textColor = button.backgroundColor;
        }
        else if (wself.cardView.backGroundColorButton == button)
        {
            wself.cardView.backgroundColor = color;
        }
    };

}

- (void)showInView:(UIView *)view
{
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    self.frame = view.bounds;
    
    CGRect cardFrame = _cardView.frame;
    cardFrame.size = self.cardSize;
    cardFrame.origin.x = 0.5 * (view.bounds.size.width - cardFrame.size.width);
    cardFrame.origin.y = view.bounds.size.height;
    _cardView.frame = cardFrame;
    
    [UIView animateWithDuration:0.3 animations:^{
        CGPoint cardCenter = self.cardView.center;
        cardCenter.y = 0.5 * view.bounds.size.height;
        self.cardView.center = cardCenter;
    }];
    
    [view addSubview:self];
}

- (FMColorPickerView *)colorPickerView
{
    if (!_colorPickerView)
    {
        FMColorPickerView *colorPickerView = [[FMColorPickerView alloc] init];
        [self addSubview:colorPickerView];
        _colorPickerView = colorPickerView;
        [self layoutColorView];
    }
    return _colorPickerView;
}

- (void)layoutColorView
{
    CGFloat cpWH = 0.5 * (self.bounds.size.height - self.cardSize.height);
    CGFloat cpy = self.bounds.size.height - cpWH;
    _colorPickerView.frame = CGRectMake(0, cpy, self.bounds.size.width, cpWH);
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self layoutColorView];
}

- (void)dismiss
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect cardFrame = self.cardView.frame;
        cardFrame.origin.y = self.bounds.size.height;
        self.cardView.frame = cardFrame;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    if (!_colorPickerView.hidden)
    {
        _colorPickerView.hidden = NO;
        return;
    }
    
    if ([self.cardView.titleTextField isFirstResponder] || [self.cardView.descTextView isFirstResponder])
    {
        [self endEditing:YES];
        return;
    }
    
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    if (!CGRectContainsPoint(self.cardView.frame, point))
    {
        [self dismiss];
    }
}

@end
